

import 'package:huajianshe_app/constants/constant.dart';
import 'package:huajianshe_app/utils/SpUtil.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';

class App {
  /// 获取用户是否在线
  static bool isLogin() {
    return SpUtil.getString(Constant.KEY_TOKEN).isNotEmpty;
  }

  static void loginSuccess(String token, [String? imId, String? imPwd]) {
    SpUtil.putString(Constant.KEY_TOKEN, token);
    saveHxId(imId, imPwd);
  }

  static void saveHxId(String? imId, String? imPwd) {
    if (imId?.isNotEmpty == true) SpUtil.putString(Constant.KEY_IM_ID, imId!);
    if (imPwd?.isNotEmpty == true) SpUtil.putString(Constant.KEY_IM_PWD, imPwd!);
    loginImIfNeeded(imId, imPwd);
  }

  static void exitLogin() {
    SpUtil.remove(Constant.KEY_TOKEN);
    SpUtil.remove(Constant.KEY_IM_ID);
    SpUtil.remove(Constant.KEY_IM_PWD);
    try {
      EMClient.getInstance.logout();
    } on EMError catch (e) {
      print('操作失败，原因是: $e');
    }
  }

  static void loginImIfNeeded([String? imId, String? imPwd]) {
    print('loginImIfNeeded: $imId $imPwd');
    if (imId == null || imId == '') imId = SpUtil.getString(Constant.KEY_IM_ID);
    if (imPwd == null || imPwd == '') imPwd = SpUtil.getString(Constant.KEY_IM_PWD);
    if (imId.isNotEmpty && imPwd.isNotEmpty) {
      print('try to login huanxin $imId $imPwd');
      try {
        EMClient.getInstance.login(imId, imPwd);
      } on EMError catch (e) {
        print('操作失败，原因是: $e');
      }
    }
  }

  static bool isImLogin() {
    return EMClient.getInstance.isLoginBefore;
  }

  // static void loginImTest() {
  //   print('loginImTest');
  //   try {
  //     EMClient.getInstance.login('vart', '123456');
  //   } on EMError catch (e) {
  //     print('操作失败，原因是: $e');
  //   }
  // }
}